package com.mihe.gateway.config;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Administrator
 */
@Component
public class SwaggerProvider implements SwaggerResourcesProvider {
    /**
     * Swagger2默认的url后缀
     */
    public static final String SWAGGER2URL = "/v2/api-docs";
    /**
     * 网关路由
     */
    @Autowired
    private DiscoveryClientRouteDefinitionLocator routeLocator;

    @Autowired
    private GatewayProperties gatewayProperties;

    public static final String SUB_PRIX = "ReactiveCompositeDiscoveryClient_";

    List<SwaggerResource> swaggerResources = Lists.newArrayList();

    Set<String> gloableSet = new HashSet<>();

    /**
     * 聚合其他服务接口
     *
     * @return
     */
    @Override
    public List<SwaggerResource> get() {
        //从DiscoveryClientRouteDefinitionLocator 中取出routes，构造成swaggerResource
        Set<String> resourceSet = new HashSet<>();

        if (swaggerResources.size() > 0) {
            for (SwaggerResource swaggerResource : swaggerResources) {
                gloableSet.add(swaggerResource.getName());
            }
        }

        routeLocator.getRouteDefinitions().subscribe(routeDefinition -> {
            resourceSet.add(routeDefinition.getId().substring(SUB_PRIX.length()));

            if (!gloableSet.contains(routeDefinition.getId().substring(SUB_PRIX.length()))) {
                if(routeDefinition.getId().contains("gateway") ) {
                    return;
                }
                swaggerResources.add(swaggerResource(routeDefinition.getId().substring(SUB_PRIX.length()),
                        routeDefinition.getPredicates().get(0).getArgs().get("pattern").replace("/**", SWAGGER2URL)));
            }
        });

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        swaggerResources.removeIf(swaggerResource -> !resourceSet.contains(swaggerResource.getName()));

        return swaggerResources;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}
